import React, { useState, useEffect, useCallback } from "react";
import { Table, Button, message, Pagination, Input, Modal } from "antd";
import { IAddStudent } from "@/interface/student";
import AddStudent from "@/component/addStudent";
import { debounce } from "lodash";
import useData from "@/store";
import api from "@/fetch";

import "./index.less";

const ManageStudent: React.FC = () => {
  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [loading, setLoading] = useState(false);
  const [isShowDelModel, setIsShowDelModel] = useState(false);
  const [isShowEditModel, setIsShowEditModel] = useState(false);
  const [studentData, setStudentData] = useState<IAddStudent>();
  const [searchParams, setSearchParams] = useState<{
    studentName: string;
    schoolName: string;
  }>({
    studentName: "",
    schoolName: "",
  });
  const { asSuperManager } = useData((state) => ({
    asSuperManager: state.userInfo?.asSuperManager,
    asSchoolManager: state.userInfo?.asSchoolManager,
  }));

  const fetchData = useCallback(
    debounce(async (currentPage, pageSize, searchParams) => {
      setLoading(true);

      const search: Partial<{ studentName: string; schoolName: string }> = {};

      if (searchParams.studentName !== "") {
        search["studentName"] = searchParams.studentName;
      }

      if (searchParams.schoolName !== "") {
        search["schoolName"] = searchParams.schoolName;
      }

      const params = {
        ...search,
        page: currentPage - 1,
        pageSize,
        // asSchoolManager: window.useData.getState().userInfo?.asSchoolManager,
        // asSuperManager: window.useData.getState().userInfo?.asSuperManager,
      };

      try {
        const res = await api.get("/api/v1/admin/student/page", params);
        setData(res.data.result);
        setTotal(res.data.total);
      } catch (error) {
        message.error(error?.message || "获取学生列表失败");
      } finally {
        setLoading(false);
      }
    }, 300),
    [],
  );

  useEffect(() => {
    fetchData(currentPage, pageSize, searchParams);
  }, [currentPage, pageSize, searchParams]);

  const handlePageChange = (newPage: number, newPageSize: number) => {
    currentPage !== newPage && setCurrentPage(newPage);
    pageSize !== newPageSize && setPageSize(newPageSize);
  };

  const handleSearchChange = (field: string, value: string) => {
    setSearchParams({
      ...searchParams,
      [field]: value,
    });
  };

  const handleResult = async (student: IAddStudent, isDel: boolean) => {
    if (isDel) {
      setStudentData(student);
      setIsShowDelModel(true);
    } else {
      setStudentData(student);
      setIsShowEditModel(true);
    }
  };

  const editSuccess = () => {
    setIsShowEditModel(false);
    fetchData(currentPage, pageSize, searchParams);
  };

  const delStudent = async () => {
    try {
      await api.post("/api/v1/admin/student/student/delete", {
        studentId: studentData?.studentId,
      });
      fetchData(currentPage, pageSize, searchParams);
      message.success("删除学生成功");
    } catch (error) {
      message.error(error?.message || "删除学生失败");
    } finally {
      setIsShowDelModel(false);
    }
  };

  const columns = [
    { title: "学校名", dataIndex: "schoolName", key: "schoolName" },
    { title: "学号", dataIndex: "studentNumber", key: "studentNumber" },
    { title: "姓名", dataIndex: "studentName", key: "studentName" },
    { title: "身高(cm)", dataIndex: "height", key: "height" },
    { title: "体重(kg)", dataIndex: "weight", key: "weight" },
    {
      title: "性别",
      dataIndex: "gender",
      key: "gender",
      render: (gender: number) => (gender === 0 ? "男" : "女"),
    },
    { title: "家长手机号", dataIndex: "parentPhone", key: "parentPhone" },
    {
      title: "操作",
      dataIndex: "actions",
      key: "actions",
      render: (_: string, student: IAddStudent) => {
        return (
          <span>
            <Button type="primary" onClick={() => handleResult(student, false)}>
              编辑
            </Button>
            <Button
              danger
              onClick={() => handleResult(student, true)}
              style={{ marginLeft: "8px" }}
            >
              删除
            </Button>
          </span>
        );
      },
    },
  ];

  return (
    <div className="manage-student-container">
      {!window.useData.getState().userInfo?.token && (
        <h1>没有登录，发送请求都是失败的噢</h1>
      )}
      <div className="manage-student-header">
        {asSuperManager && (
          <Input
            allowClear
            className="custom-input"
            placeholder="搜索学校"
            value={searchParams.schoolName}
            style={{ marginRight: "12px" }}
            onChange={(e) => handleSearchChange("schoolName", e.target.value)}
          />
        )}
        <Input
          allowClear
          className="custom-input"
          placeholder="搜索学生姓名"
          value={searchParams.studentName}
          onChange={(e) => handleSearchChange("studentName", e.target.value)}
        />
      </div>

      <Table
        dataSource={data}
        columns={columns}
        pagination={false}
        loading={loading}
      />
      <Pagination
        current={currentPage}
        pageSize={pageSize}
        total={total}
        onChange={handlePageChange}
        showSizeChanger
        pageSizeOptions={["10", "20", "50", "100"]}
        style={{ marginTop: "16px", textAlign: "right" }}
      />
      <Modal
        open={isShowEditModel}
        onCancel={() => setIsShowEditModel(false)}
        footer={null}
      >
        <AddStudent
          isEdit
          student={studentData}
          editSuccess={editSuccess}
        ></AddStudent>
      </Modal>
      <Modal
        open={isShowDelModel}
        onOk={delStudent}
        onCancel={() => setIsShowDelModel(false)}
      >
        <div>确定删除该学生吗？</div>
      </Modal>
    </div>
  );
};

export default ManageStudent;
